﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;

namespace PowerPatcher
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private bool IsAdministrator
        {
            get
            {
                return new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
            }
        }
        protected override void OnStartup(StartupEventArgs e)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            AssemblyResolver.Register();

            System.Threading.Thread.CurrentThread.CurrentUICulture = PowerPatcher.Properties.Settings.Default.Culture;

            System.IO.File.Delete("PowerPatcher.log");

            Helper.WriteLogLine("PowerPatcher starting up. Command Line arguments: " + string.Join("\t", e.Args));
            string cwd = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
            Helper.WriteLogLine("Current directory: \"" + Environment.CurrentDirectory + "\"\tSetting CWD to: " + cwd);
            Environment.CurrentDirectory = cwd;

            string nxdir = (string)Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Software\Nexon\Mabinogi", null, "Not installed");

            Helper.WriteLogLine("Mabinogi directory: " + nxdir);


            if (nxdir == null || nxdir == "Not installed")
            {
                System.Windows.Forms.MessageBox.Show(Msgs.OopsItAppearsThatMabinogiIsnTInstalled, Msgs.Error, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                Helper.WriteLogLine("FATAL ERROR: Nexon regkey not found...");
                Application.Current.Shutdown(0);
                return;
            }

            if (String.Compare(System.IO.Path.GetFullPath(nxdir).TrimEnd('\\'), System.IO.Path.GetFullPath(cwd).TrimEnd('\\'), StringComparison.InvariantCultureIgnoreCase) != 0)
            {
                System.Windows.Forms.MessageBox.Show(string.Format(Msgs.WarningPowerPatcherIsNOTLocatedInTheMabino, nxdir), Msgs.Warning, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                Helper.WriteLogLine("WARNING: PowerPatcher is not located in the Mabinogi directory.");
            }

            List<string> args = new List<string>();
            for (int i = 0; i < e.Args.Length; i++)
                args.Add(e.Args[i].ToLower());

            if (args.Contains("/uninstall"))
                uninstall();
            if (args.Contains("/noadmin"))
                PowerPatcher.Properties.Settings.Default.RequireAdministrator = false;
            if (args.Contains("/nostart"))
                PowerPatcher.Properties.Settings.Default.StartAfterPatch = false;

            Application.Current.Properties["StartArgs"] = e.Args;

            //Check if we're an admin
            if (PowerPatcher.Properties.Settings.Default.RequireAdministrator && !IsAdministrator)
            {
                System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo();
                proc.UseShellExecute = true;
                proc.WorkingDirectory = Environment.CurrentDirectory;
                proc.FileName = System.Windows.Forms.Application.ExecutablePath;
                proc.Arguments = "";
                foreach (string s in e.Args)
                    proc.Arguments += s + " ";
                proc.Verb = "runas";
                try
                {
                    System.Diagnostics.Process.Start(proc);
                }
                catch
                {
                    // The user refused the elevation.
                    System.Windows.Forms.MessageBox.Show(PowerPatcher.Msgs.ThisProgramRequiresAdministrativePrivelidg, PowerPatcher.Msgs.Error, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
                Environment.Exit(0);
            }

            base.OnStartup(e);
            Helper.WriteLogLine("Application initialized successfully. Loading/displaying main window.");
        }
        protected override void OnExit(ExitEventArgs e)
        {
            PowerPatcher.Properties.Settings.Default.Save();
            base.OnExit(e);
        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                Helper.WriteLogLine("APP CRASHING: " + ((Exception)e.ExceptionObject).ToString());
                PowerPatcher.Properties.Settings.Default.Save();
                ErrorReport er = new ErrorReport((Exception)e.ExceptionObject);
                er.ShowDialog();
            }
            finally
            {
                PowerPatcher.Properties.Settings.Default.Save();
                Environment.Exit(1);
            }
        }
        void uninstall()
        {
            using (Uninstaller u = new Uninstaller())
            {
                if (u.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    Environment.Exit(0);
            }
        }
    }
}
